package com.captain.leetcode.中级.数组;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Des:
 *
 * @author XL
 * @Date 2022/1/10 15:35
 */
public class 三数之和15 {

    public static void main(String[] args) {
        System.out.println(new 三数之和15().threeSum(new int[1]));
    }

    public List<List<Integer>> threeSum(int[] nums) {
        if (nums == null) return null;
        List<List<Integer>> res = new ArrayList<>();
        //解题思路
        //选定一个target = -target = 值1 + 值2 = 0;
        //排序
        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 2; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) {
                //如果值相同,则跳过
                continue;
            }
            //排序后后面的值不可能等式实现
            if (nums[i] > 0) {
                break;
            }
            int left = i + 1;
            int right = nums.length - 1;
            int target = -nums[i];
            //寻找两个值相加 等于 -target;
            while (left < right) {
                int sum = nums[left] + nums[right];
                if (sum == target) {
                    res.add(Arrays.asList(nums[i], nums[left], nums[right]));
                    //过滤掉重复的
                    while (left < right && nums[left] == nums[right]) {
                        left++;
                    }
                    while (left < right && nums[right] == nums[right - 1]) {
                        right--;
                    }
                    left++;
                    right--;
                } else if (sum < target) {
                    left++;
                } else {
                    right--;
                }
            }
        }
        return res;
    }
}
